import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:flutterapp2/building/buildinfo.dart';
import 'package:flutterapp2/building/buildingwidget.dart';

/// gridview不能指定子view固定宽度，间距自动算，而且不能指名高度，只能设置宽高比
class BuildingMainPage extends StatefulWidget {
  // 选中的
  final List<BuildInfo> selected;

  @override
  State<StatefulWidget> createState() => _BuildState();

  BuildingMainPage({Key key, this.selected}) : super(key: key);
}

class _BuildState extends State<BuildingMainPage> {
  List<BuildInfo> _data;
  List<BuildInfo> selected;
  int selectedNum = 0;

  @override
  void initState() {
    super.initState();
    this.selected = widget.selected;

    // 模拟网络请求
    /// 最好是外面请求数据，避免每次进来都请求数据
    rootBundle.loadString('assets/files/data.json').then((value) {
      _data = (json.decode(value) as List)
          .map((mapJson) => BuildInfo.fromJson(mapJson))
          .toList();
      _checkSelected();
      _update();
    });
  }

  void _update() {
    setState(() {});
  }

  // 校验选中的
  void _checkSelected() {
    if (selected == null) return;
    _data.forEach((item) {
      for (var buildInfo in selected) {
        if (buildInfo.id == item.id) {
          item.isSelected = true;
          selectedNum++;
          break;
        }
      }
    });
  }

  void _selectedAll() {
    _data.forEach((item) {
      item.isSelected = true;
    });
    selectedNum = _data.length;
    _update();
  }

  void _onConfirm() {
    List<BuildInfo> selectedData = new List();
    _data.forEach((item) {
      if (item.isSelected) {
        selectedData.add(item);
      }
    });
    Navigator.of(context).pop(selectedData);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("选择绑定楼栋"),
        actions: <Widget>[
          FlatButton(
              child: Text("全选"),
              textColor: Colors.white,
              onPressed: () {
                _selectedAll();
              })
        ],
      ),
      body: Stack(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.fromLTRB(23, 14, 18, 14),
            child: GridView.builder(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  mainAxisSpacing: 10,
                  crossAxisCount: 4,
                  crossAxisSpacing: 10,
                  childAspectRatio: 76 / 34),
              itemCount: _data == null ? 0 : _data.length,
              itemBuilder: (context, index) =>
                  BuildingWidget(_data[index], (num) {
                selectedNum += num;
                _update();
              }),
            ),
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              width: 335,
              height: 50,
              margin: EdgeInsets.only(bottom: 16),
              decoration: BoxDecoration(
                color: Color(0xFF21C1B5),
                borderRadius: BorderRadius.circular(4),
              ),
              child: FlatButton(
                onPressed: () {
                  _onConfirm();
                },
                textColor: Colors.white,
                child: Text(
                  "确定($selectedNum)",
                  style: TextStyle(
                    fontSize: 16,
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}
